/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import controller.EventManager;
import controller.InvitationManager;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import entity.Event;
import entity.Invitation;
import entity.User;
import java.io.IOException;
import java.util.Calendar;
import java.util.Collections;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import org.primefaces.json.JSONException;
import utility.Forecast;
import org.primefaces.json.JSONArray;
import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;

/**
 *
 * @author xubuntu
 */
@ManagedBean
@SessionScoped
public class PersonalPageBean implements Serializable {

    @ManagedProperty(value = "#{loginBean}")
    private LoginBean wlmPage;
    @ManagedProperty( value = "#{weatherBean}" )
    private WeatherBean weatherBean;
    @ManagedProperty( value = "#{navigationBean}" )
    private NavigationBean navigationBean;

    @EJB
    private EventManager evtMgr;
    @EJB
    private InvitationManager invMgr;
    
    private Date today;
    
    private User userSelected;
    private Event eventSelected;
    int noAnswer;

    /*
    * le due liste seguenti contengono gli eventi che generano una notifica
    */
    private List<Event> eventPassed;
    private List<Event> eventDeclined;
    private List<Event> eventsTakePart;
    private List<Event> eventsOrganized;
    private List<Event> weatherNotifications;
    private List<Event> invitationsPending;
    private List<Invitation> invitations;
    private List<Forecast> badWeathers;
   

    @PostConstruct
    public void init() {    
        today= new Date();
        noAnswer = 0;
        eventsTakePart = wlmPage.getEventsTakePart();
        eventsOrganized = wlmPage.getEventsOrganized();
        eventPassed= wlmPage.getEventPassed();
        eventSelected = new Event();
        eventSelected.setName("");
        eventDeclined= evtMgr.getAllEventsDeclined(wlmPage.getUser());
        invitationsPending = new ArrayList<Event>();
        weatherNotifications = new ArrayList<Event>();
        invitations = invMgr.getAllInvitationUser(wlmPage.getUser());
        badWeathers = weatherBean.getAllBadWeathers(wlmPage.getWeathers());
        
        listPassedControl();
        Collections.sort(eventsTakePart);
        Collections.sort(eventPassed);
        Collections.sort(eventDeclined);
        
        
        
     }
   

    /* updateNotification:
     * controlla se ci sono inviti ai quali non è stato risposto
     * controlla le condizioni meteo degli eventi programmati
     */
    public String updateNotification() throws JSONException, IOException {

        Date firstDaySunny = new Date();
        System.out.println("Controllo notifiche");
        if(invitations!= null && invitations.isEmpty()== false){
            for(Invitation i: invitations){
                if(invitationsPending.contains(i.getEvent())==false){
                    if(i.getAnswer()== noAnswer && i.getEvent().getDateStart().before(today)== false){
                        invitationsPending.add(i.getEvent());
                        System.out.println("utente invitato all'evento: "+i.getEvent().getName());
                        
                    }
                }else{
                   if(i.getAnswer()!=noAnswer){
                       invitationsPending.remove(i.getEvent());
                    }
                }
            }
        }
        

        /*
         * eventi a 3 giorni
         */
        
        if(badWeathers != null && badWeathers.isEmpty()== false && eventsOrganized!= null && eventsOrganized.isEmpty() == false){
            for(Event e: eventsOrganized){
                if(weatherNotifications.contains(e)==false){
                    long differenzaGiornilong = e.getDateStart().getTime()-today.getTime();
                    int differenzaGiorni = Math.round(differenzaGiornilong/86400000)+1;
                    if((e.getTypeIo()== 1)&&( differenzaGiorni == 3)){
                        for(Forecast f: badWeathers){
                            if(e.getPlace().equalsIgnoreCase(f.getPlace())){
                                
                                
                                // cerco primo meteo sereno
                                Date d = weatherBean.searchSunny(e,differenzaGiorni);
                                e.setFirstDate(d);
                                weatherNotifications.add(e);
                                System.out.println("Notifica di evento organizzato: " +e.getName());
                                System.out.println("primo giorno soleggiato: " +e.getFirstDate().toString());
                            }
                        }
                    }
                }
            }
        }
        /*
         * eventi a 1 giorno
         */
        if(eventsTakePart != null && eventsTakePart.isEmpty()== false){
            for(Event e: eventsTakePart){
                if(weatherNotifications.contains(e)==false){
                    long differenzaGiornilong = e.getDateStart().getTime()-today.getTime();
                    int differenzaGiorni = Math.round(differenzaGiornilong/86400000)+1;

                    if((e.getTypeIo()== 1)&&(differenzaGiorni== 1)&&(badWeathers.isEmpty()==false)){
                        for(Forecast f: badWeathers){
                            if(e.getPlace().equalsIgnoreCase(f.getPlace())){
                                // cerco primo meteo sereno
                                e.setFirstDate(weatherBean.searchSunny(e,differenzaGiorni));
                                weatherNotifications.add(e);
                                System.out.println("Notifica di evento partecipante: " +e.getName());
                                System.out.println("primo giorno soleggiato: " +e.getFirstDate().toString());
                                
                            }
                        }
                    }
                }
            }
        }
     return navigationBean.redirectToNotificationsPage();
    }


    
    public String eventTypePp(Event e) {
        if (e.getTypePp() == 0) {
            return "Private";
        } else {
            return "Public";
        }
    }
    
    public String eventTypeIo(Event e) {
        if (e.getTypeIo() == 0) {
            return "Indoor";
        }else {
            return "Outdoor";
        }
    }

    private void listPassedControl(){
        if(invitations!= null && invitations.isEmpty()== false){
            for(Invitation i: invitations){
                if(i.getAnswer()== 2 && i.getEvent().getDateStart().before(today)== true){
                    eventPassed.remove(i);
                }
            }
        }
    }
            
       public User getUserSelected() {
        return userSelected;
    }

    public void setUserSelected(User userSelected) {
        this.userSelected = userSelected;
    }

    public Event getEventSelected() {
        return eventSelected;
    }

    public void setEventSelected(Event eventSelected) {
        this.eventSelected = eventSelected;
    }
	
    
    public WeatherBean getWeatherBean() {
        return weatherBean;
    }

    public void setWeatherBean(WeatherBean weatherBean) {
        this.weatherBean = weatherBean;
    }

    public Date getToday() {
        return today;
    }

    public void setToday(Date today) {
        this.today = today;
    }

    public int getNoAnswer() {
        return noAnswer;
    }

    public void setNoAnswer(int noAnswer) {
        this.noAnswer = noAnswer;
    }
    
   
    public List<Event> getEventsTakePart() {
        return eventsTakePart;
    }
 

    public List<Event> getEventsOrganized() {
        return eventsOrganized;
    }
    
    public List<Event> getEventPassed() {
        return eventPassed;
    }

    public void setEventPassed(List<Event> eventPassed) {
        this.eventPassed = eventPassed;
    }

    public List<Event> getEventDeclined() {
        return eventDeclined;
    }

    public void setEventDeclined(List<Event> eventDeclined) {
        this.eventDeclined = eventDeclined;
    }

    
    public LoginBean getWlmPage() {
        return wlmPage;
    }

    public void setWlmPage(LoginBean wlmPage) {
        this.wlmPage = wlmPage;
    }

    public NavigationBean getNavigationBean() {
        return navigationBean;
    }

    public void setNavigationBean(NavigationBean navigationBean) {
        this.navigationBean = navigationBean;
    }

    public List<Event> getWeatherNotifications() {
        return weatherNotifications;
    }

    public void setWeatherNotifications(List<Event> weatherNotifications) {
        this.weatherNotifications = weatherNotifications;
    }

    public List<Event> getInvitationsPending() {
        return invitationsPending;
    }

    public void setInvitationsPending(List<Event> invitationsPending) {
        this.invitationsPending = invitationsPending;
    }
    
    
    
}
